/**
 * Created by aesop on 2015/4/19.
 */

var add_people = document.getElementById("addPeople");
var remove_people = document.getElementById("removePeople");
var add_people_list = document.getElementsByClassName("nova-note-send-people-query")[0];
var remove_people_list = document.getElementsByClassName("nova-note-send-people-query")[1];
var group_list = document.getElementById("groupList");
var people_list = document.getElementById("peopleList");

var active_li = -1;
var previous_active = -1;



add_people.onclick = function(e){
     e = e || window.event;
    if(e.stopPropagation) { //W3C阻止冒泡方法
        e.stopPropagation();
    } else {
        e.cancelBubble = true; //IE阻止冒泡方法
    }
    var value = add_people.value;
    add_people_list.innerHTML = gen_li(value);
    is_lock = false;
}
add_people.onfocus = function(){
    add_people_list.className = 'nova-note-send-people-query';
}
add_people.onblur = function(){
    removeChildrenClass(add_people_list.children);

    active_li = -1;
    previous_active = -1;
}
//remove_people.onblur = function(){
//
//    removeChildrenClass(remove_people_list.children);
//    active_li = -1;
//    previous_active = -1;
//}

function removeChildrenClass(list){
    for(var i =0 ; i < list.length; i ++){
        list[i].className = '';
    }
}
/**
 * Down Arrow:40
 * Up Arrow : 38
 * @param e
 */
var is_lock = false;
add_people.onkeydown = function(e){
    e = e || window.event;
    var code = e.keyCode;
    //alert(code);
    if(code == 40){
        is_lock = true;
        if(previous_active >= add_people_list.children.length-1)
            active_li = -1;
        try{
            add_people_list.children[previous_active].className = ""
        }
        catch (e){

        }
        active_li += 1;
        add_people_list.children[active_li].className = 'active';
        add_people.value = add_people_list.children[active_li].innerHTML;
         previous_active = active_li;

    }
    else if(code == 38){
        is_lock = true;
         if(previous_active <=0)
            active_li = add_people_list.children.length;

        try{
          add_people_list.children[previous_active].className = ""
        }
        catch (e){

        }
        active_li -=1;
        add_people_list.children[active_li].className = 'active';
        add_people.value = add_people_list.children[active_li].innerHTML;
         previous_active = active_li;
    }
    //@TODO
    else if(code == 13 ){
        is_lock = true;
        var value = add_people.value;
        if(value){
             add_group(value);
        }

    }
    else{
        is_lock = false;
    }
}

add_people.onkeyup = function(){
    if(!is_lock){
            var value = add_people.value;
        add_people_list.innerHTML = gen_li(value);
    }

}
document.getElementById("suggest-list").onclick = function(e){
    e = e || window.event;
    var target = e.target;

    var value = target.innerText;
    add_group(value);

}
document.body.onclick = function(){
    add_people_list.className = 'nova-note-send-people-query hidden';
    is_lock = false;

}

//下面是发送人员的操作

//@TODO id待定
var group_sample = document.getElementById("groupSample");
var person_sample = document.getElementById("personSample");



var storage =  {};

storage.group = {};
storage.people = {};
people_to_array = function(people){
    var that = people;
    var arr = [];
    if(that){
        for( var index in that){
            arr[arr.length] = that[index]['stu_id'];
        }
    }
    return arr;
}

function EachPerson(stu_id, name){
    this.stu_id = stu_id;
    this.name = name;
    this.refered = 1;
}
EachPerson.prototype.add_refer = function(){
    this.refered += 1;
}
EachPerson.prototype.minus_refer = function(){
    this.refered -= 1;
    if(this.refered <=0){
        remove_person_dom(this);
        delete storage.people[this.stu_id]
    }
}
EachPerson.prototype.equals = function(b){
    if(b instanceof EachPerson){
        if(b.stu_id == this.stu_id){
            return true;
        }
        else{
            return false;
        }
    }
    return false;
}
//若小返回1
EachPerson.prototype.compare = function(b){
     if(!b instanceof EachPerson){
         return -1;
     }
    else{
         if(b.stu_id > this.stu_id){
             return 1;
         }
         else if(b.stu_id == this.stu_id){
             return 0;
         }
         else{
             return-1;
         }
     }
}

//增加一个发送组别
function add_group(group_name){
    if(! storage.group[group_name ]){
        storage.group[group_name] = friendly_group[group_name];
        var people_list = friendly_group[group_name]["group_member"];
        people_list.forEach(function(value){
        if(storage.people[value.stu_id]){
            storage.people[value.stu_id].add_refer();
        }
        else{
            storage.people[value.stu_id] = new EachPerson(value.stu_id, value.name);
            add_person_dom(storage.people[value.stu_id]);
        }

         });
        add_group_dom(group_name);

    }

}

function remove_group(group_name){
    var people_list = friendly_group[group_name]["group_member"];
    people_list.forEach(function(value){
        try{
           storage.people[value.stu_id].minus_refer();
        }
        catch(e){
            ;
        }
    });
    delete storage.group[group_name];
    remove_group_dom(group_name)
}

function remove_stu(stu_id){
    delete storage.people[stu_id];
    remove_person_dom({stu_id:stu_id});
}



//增加一组的dom操作
function add_group_dom(group_name){
    var new_node = group_sample.cloneNode(true);
    new_node.className = ""
    new_node.id= group_name;
    new_node.children[1].innerText = group_name;
    group_list.appendChild(new_node);;
}
function remove_group_dom(group_name){
    var node = document.getElementById(group_name);
    node.parentNode.removeChild(node);
}

//增加接受人员的操作
function add_person_dom(person){
    var new_node = person_sample.cloneNode(true);
    new_node.id = person.stu_id;
    new_node.className = "";
    new_node.children[1].innerText = person.name + " " + person.stu_id;
    people_list.appendChild(new_node);
}
function remove_person_dom(person){
    var node = document.getElementById(person.stu_id);
    node.parentNode.removeChild(node);
}

//
//处理删除
group_list.onclick = function(e){
    e = e || window.event;
    var target = e.target;
    if(target.className == "nova-note-send-people-del" || target.tagName == 'I'){
        var node = target.parentNode;
        remove_group(node.id || node.parentNode.id);
    }
}
people_list.onclick = function(e){
    e = e || window.event;
    var target = e.target;
    if(target.className == "nova-note-send-people-del" || target.tagName == 'I'){
        var node = target.parentNode;
        remove_stu(node.id || node.parentNode.id);
    }
}

//初始化
//数据源部分
var all_groups = [];
var dic = {};
var key = "";
var friendly_group = {};



function add_dic(key, value){
    dic[key] = dic[key] || [];
    dic[key][dic[key].length] = value;
}

function initial_dic(){
    all_groups.forEach(function(value){
        for(var j = 0; j < value.group_name.length; j++){
            if(j == value.group_name.length -1){
                add_dic(value.group_name[j], value);
            }
            else{
                for(var k = j; k < value.group_name.length;k ++){
                 key = value.group_name.slice(j,k+1);
                 add_dic(key, value);
            }
            }
        }
        friendly_group[value.group_name] = value;

    });

}

function gen_li(key){
    if(key in dic){
        var list = dic[key];
        var html = "";
        list.forEach(function(value){
            html += "<li>"+ value.group_name +"</li>"
        })
        return html;
    }
    else if(!key){
        var html = "";
        for(var item in friendly_group){
            html += "<li>"+ item +"</li>"
        }
        return html;
    }
    else{
        return "<li></li>";
    }
}

$().ready(function(){
    $.get('/note/group/list', function(data){
        all_groups = JSON.parse(data);
        initial_dic();
    })
});

add_people.value = ""


//使用js提交表单(POST请求)
document.getElementById("nova-note-send-submit").onclick = function(){
    if(storage.people){
        var note_type = document.getElementsByTagName("select")[0].value;
        var title = document.getElementById("note-title").value;
        title = title ? title:(note_type? "文章一则":"通知一条");
         $.post('/note/send',{
                 people_list:'[' + people_to_array(storage.people).toString() +']',
                 note_type:note_type,
                 title:title
             },function(data, status){
            if( data == 0){
                location.href = "/note/history"
            }
            else{
                alert(data);
            }
        }
    )
    }
    else{
        alert("请先选人！");
    }

}